const User = require('../models/User')
const UserProfile = require('../models/UserProfile')

// 用户注册事务处理服务
exports.handleUserRegistration = async userData => {
	let user, profile
	try {
		// 注册用户
		user = await User.create(userData)

		// 创建用户配置
		profile = await UserProfile.create({
			userId: user._id,
			preferences: { theme: 'light' }
		})
		return { user, profile }
	} catch (error) {
		if (user) await User.deleteOne({ _id: user._id })
		if (profile) await UserProfile.deleteOne({ userId: user._id })
		throw new Error(`用户注册失败: ${error.message}`)
	}
}
